package server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {
	private Server server;
	private Socket socket;
	private PrintWriter out;
	private BufferedReader in;
	private String name;

	public Client(Server server, Socket socket) {
		this.server = server;
		this.socket = socket;

		try {
			out = new PrintWriter(socket.getOutputStream());
			in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void send(String data) {
		try {
			out.println(data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void listen() {
		new Thread() {
			public void run() {
				while (server.isRunning()) {
					try {
						String data;
						while ((data = in.readLine()) != null) {
							process(data);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
	}

	private void process(String data) {
		server.process(this, data);
	}

	public String getName() {
		return name;
	}

	public void disconnect() {
		try {
			out.close();
			in.close();
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setName(String s) {
		name = s;
	}
}
